namespace Maple.Branch.AuthServer.Controllers
{
    using System;
    using System.Globalization;
    using System.Runtime.InteropServices;
    using System.Threading.Tasks;
    using IdentityServer4.Services;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Hosting;
    using Models;
    using Volo.Abp.Localization;

    [SecurityHeaders]
    [AllowAnonymous]
    public class HomeController : Controller
    {
        private readonly IIdentityServerInteractionService _interaction;
        private readonly IWebHostEnvironment _environment;
        private readonly ILanguageProvider _languageProvider;

        public HomeController(IIdentityServerInteractionService interaction,
                              IWebHostEnvironment environment,
                              ILanguageProvider languageProvider)
        {
            _interaction = interaction;
            _environment = environment;
            _languageProvider = languageProvider;
        }

        public async Task<IActionResult> IndexAsync()
        {
            var languages = await _languageProvider.GetLanguagesAsync();

            var currentLanguage = languages.FindByCulture(
                CultureInfo.CurrentCulture.Name,
                CultureInfo.CurrentUICulture.Name
            ) ?? languages.FindByCulture(
                CultureInfo.CurrentCulture.Parent.Name,
                CultureInfo.CurrentUICulture.Name
            );

            return View();
        }

        [HttpGet]
        [Route("monitor")]
        public IActionResult Monitor()
        {
            return Ok(new { CurrentTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm"), Env = _environment.EnvironmentName, OS = $"{RuntimeInformation.OSDescription} {RuntimeInformation.OSArchitecture}" });
        }

        /// <summary>
        /// Shows the error page
        /// </summary>
        public async Task<IActionResult> Error(string errorId)
        {
            var vm = new ErrorViewModel();

            // retrieve error details from identityserver
            var message = await _interaction.GetErrorContextAsync(errorId);
            if (message != null)
            {
                vm.Error = message;

                if (!_environment.IsDevelopment())
                {
                    // only show in development
                    message.ErrorDescription = null;
                }
            }

            return View("Error", vm);
        }
    }
}
